<template></template>
<script lang="ts">
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import GUI from 'three/examples/jsm/libs/lil-gui.module.min.js';
import { EffectComposer, GammaCorrectionShader, GlitchPass, OutlinePass, RenderPass, ShaderPass, UnrealBloomPass } from 'three/examples/jsm/Addons.js';
// 场景、相机、渲染器
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 100);
camera.position.set(0, 0, 5);

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

const controls = new OrbitControls(camera, renderer.domElement);

// 添加几个不同颜色的立方体
const cubes: any[] = [];
for (let i = -2; i <= 2; i += 2) {
    const cube = new THREE.Mesh(
        new THREE.BoxGeometry(1, 1, 1),
        new THREE.MeshStandardMaterial({ color: new THREE.Color(`hsl(${(i + 2) * 60}, 100%, 50%)`) })
    );
    cube.position.x = i;
    scene.add(cube);
    cubes.push(cube);
}

// 灯光
scene.add(new THREE.AmbientLight(0xffffff, 0.5));
const dirLight = new THREE.DirectionalLight(0xffffff, 1);
dirLight.position.set(5, 5, 5);
scene.add(dirLight);

// 射线拾取器
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();

// 鼠标点击事件
window.addEventListener('click', (event) => {
    // 计算鼠标标准设备坐标 (-1~1)
    mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
    mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;

    // 用摄像机和鼠标坐标设置射线
    raycaster.setFromCamera(mouse, camera);

    // 计算和所有立方体的交点
    const intersects = raycaster.intersectObjects(cubes);

    if (intersects.length > 0) {
        // 选中第一个交点的物体
        const selected = intersects[0].object as THREE.Mesh;
        console.log('选中了:', intersects);

        // 给选中物体改颜色，做个简单反馈
        (selected.material as THREE.MeshStandardMaterial).color.set(0xffff00);
    }
});

// 动画循环
function animate() {
    requestAnimationFrame(animate);
    controls.update();
    renderer.render(scene, camera);
}
animate();

// 窗口自适应
window.addEventListener('resize', () => {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
});
</script>